<template>
  <div
    id="gapsum"
    v-loading="loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
  >
    <el-card class="box-card">
      <div>
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="项目人员明细" name="first">
            <el-row style="margin: 25px 0 25px 0px">
                  <label for="cascader" style="margin: 10px 0 10px 0px;">选择项目:</label>
                  <el-cascader
                    placeholder="请选择项目"
                    :props="props"
                    :options="singleSelector"
                    filterable
                    clearable
                    collapse-tags
                    :show-all-levels="false"
                    @change="searchPro"
                    style="margin-left: 10px"
                  >
                  </el-cascader>
                  <span class="col-span" style="margin-left:30px">时间段：</span>
                  <el-date-picker
                      v-model="dateRange"
                      @change="changeDateRange"
                      type="daterange"
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期">
                  </el-date-picker>
                  <span class="col-span" style="margin-left:30px">项目状态：</span>
                  <el-select
                    v-model="value2"
                    multiple
                    clearable
                    collapse-tags
                    style="margin-left: 20px;"
                    placeholder="请选择"
                    @change="filterStatus($event)">
                    <el-option
                      v-for="item in statusOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
              <el-button type="warning" round style="float:right" @click="down">导出</el-button>
            </el-row>
             <!-- <div><div style="width:30px;height:20px;background:#feecbade;display: inline-block"></div> <span style="font-size:14px;font-weight:normal">未分配满</span></div>
             <div><div style="width:30px;height:20px;background:#eb070763;display: inline-block"></div> <span style="font-size:14px;font-weight:normal">未投</span></div> -->
            <el-table
              :data="tableData"
              border
              style="width: 100%"
              :header-cell-style="{ background: '#eef1f6',height:'80px' }"
              :cell-class-name="addClass"
              max-height='750'
            >
              <el-table-column prop="date" label="项目名" width="180" align="center" fixed="left">
                  <template slot-scope="scope">
                      {{ scope.row.project_name}}
                  </template>
              </el-table-column>
              <!-- <el-table-column label="事业群" width="180" align="center">
                  <template slot-scope="scope">
                    {{ scope.row.group_name}}
                  </template>
              </el-table-column> -->
              <el-table-column label="立项事业部"  width="150" align="center">
                  <template slot-scope="scope">
                    {{ scope.row.dept_name}}
                  </template>
              </el-table-column>
              <el-table-column label="项目状态" align="center" width="80">
                  <template slot-scope="scope">
                    {{ scope.row.project_status}}
                  </template>
              </el-table-column>
              <el-table-column label="员工姓名" align="center" width="180">
                  <template slot-scope="scope">
                    <div v-if="scope.row.user_info.length == '0'">
                        {{ "-" }}
                    </div>
                    <div v-if="scope.row.user_info.length == '1'">
                      <div v-for="(v,i) in scope.row.user_info" :key="i">
                        {{ v.user_name }}
                      </div>
                    </div>
                    <div v-if="scope.row.user_info.length > '1'">
                      <div v-for="(v,i) in scope.row.user_info" :key="i" class="borders">
                        {{ v.user_name }}
                      </div>
                    </div>
                  </template>
              </el-table-column>

              <el-table-column label="员工所属一级部门" align="center" width="180">
                  <template slot-scope="scope">
                      <div v-if="scope.row.user_info.length == '0'">
                        {{ "-" }}
                      </div>
                      <div v-if="scope.row.user_info.length == '1'">
                        <div v-for="(v,i) in scope.row.user_info" :key="i">
                          {{ v.department_name }}
                        </div>
                      </div>
                      <div v-if="scope.row.user_info.length > '1'">
                        <div v-for="(v,i) in scope.row.user_info" :key="i" class="borders">
                          {{ v.department_name }}
                        </div>
                      </div>
                  </template>
              </el-table-column>

              <el-table-column label="员工所属二级部门" align="center" width="180">
                  <template slot-scope="scope">
                      <div v-if="scope.row.user_info.length == '0'">
                        {{ "-" }}
                      </div>
                      <div v-if="scope.row.user_info.length == '1'">
                        <div v-for="(v,i) in scope.row.user_info" :key="i">
                          {{ v.dept2_name }}
                        </div>
                      </div>
                      <div v-if="scope.row.user_info.length > '1'">
                        <div v-for="(v,i) in scope.row.user_info" :key="i" class="borders">
                          {{ v.dept2_name }}
                        </div>
                      </div>
                  </template>
              </el-table-column>

              <el-table-column label="员工所属三级部门" align="center" width="180">
                  <template slot-scope="scope">
                      <div v-if="scope.row.user_info.length == '0'">
                        {{ "-" }}
                      </div>
                      <div v-if="scope.row.user_info.length == '1'">
                        <div v-for="(v,i) in scope.row.user_info" :key="i">
                          {{ v.dept3_name }}
                        </div>
                      </div>
                      <div v-if="scope.row.user_info.length > '1'">
                        <div v-for="(v,i) in scope.row.user_info" :key="i" class="borders">
                          {{ v.dept3_name }}
                        </div>
                      </div>
                  </template>
              </el-table-column>

              <el-table-column label="员工类型" align="center" width="180">
                  <template slot-scope="scope">
                      <div v-if="scope.row.user_info.length == '0'">
                        {{ "-" }}
                      </div>
                      <div v-if="scope.row.user_info.length == '1'">
                        <div v-for="(v,i) in scope.row.user_info" :key="i">
                          {{ v.type }}
                        </div>
                      </div>
                      <div v-if="scope.row.user_info.length > '1'">
                        <div v-for="(v,i) in scope.row.user_info" :key="i" class="borders">
                          {{ v.type }}
                        </div>
                      </div>
                  </template>
              </el-table-column>
               <el-table-column label="最后更新人" align="center" width="180">
                  <template slot-scope="scope">
                      <div v-if="scope.row.user_info.length == '0'">
                        {{ "-" }}
                      </div>
                      <div v-if="scope.row.user_info.length == '1'">
                        <div v-for="(v,i) in scope.row.user_info" :key="i">
                          {{ v.up_user }}
                        </div>
                      </div>
                      <div v-if="scope.row.user_info.length > '1'">
                        <div v-for="(v,i) in scope.row.user_info" :key="i" class="borders">
                          {{ v.up_user }}
                        </div>
                      </div>
                  </template>
              </el-table-column>
              <el-table-column label="最后更新时间" align="center" width="180">
                  <template slot-scope="scope">
                      <div v-if="scope.row.user_info.length == '0'">
                        {{ "-" }}
                      </div>
                      <div v-if="scope.row.user_info.length == '1'">
                        <div v-for="(v,i) in scope.row.user_info" :key="i">
                          {{ v.up_time }}
                        </div>
                      </div>
                      <div v-if="scope.row.user_info.length > '1'">
                        <div v-for="(v,i) in scope.row.user_info" :key="i" class="borders">
                          {{ v.up_time }}
                        </div>
                      </div>
                  </template>
              </el-table-column>

              <el-table-column label="人员技术领域" align="center" width="180">
                  <template slot-scope="scope">
                      <div v-if="scope.row.user_info.length == '0'">
                        {{ "-" }}
                      </div>
                      <div v-if="scope.row.user_info.length == '1'">
                        <div v-for="(v,i) in scope.row.user_info" :key="i">
                          <el-tooltip placement="top" effect="light">
                              <div slot="content" v-for="(val,ind) in v.technical_field_names" :key="ind">
                                <div style="line-height: 20px">{{val}}</div>
                              </div>
                              <div v-for="(val,ind) in v.technical_field_names" :key="ind">
                                <el-tag type="primary">{{val.length > 8 ? val.substring(0,13) + '...' : val + '...'}}</el-tag>
                              </div> 
                            </el-tooltip>
                        </div>
                      </div>
                      <div v-if="scope.row.user_info.length > '1'">
                        <div v-for="(v,i) in scope.row.user_info" :key="i" class="borders">
                           <el-tooltip placement="top" effect="light">
                              <div slot="content" v-for="(val,ind) in v.technical_field_names" :key="ind">
                                <div style="line-height: 20px">{{val}}</div>
                              </div>
                              <div v-for="(val,ind) in v.technical_field_names" :key="ind">
                                <el-tag type="primary">{{val.length > 8 ? val.substring(0,13) + '...' : val + '...'}}</el-tag>
                              </div> 
                            </el-tooltip>
                        </div>
                      </div>
                  </template>
              </el-table-column>
              <el-table-column align="center" type="cell" v-for="(v,i) in weekList" :key="i" :property="v" :label="week2date(v)" width="180">
                  <template slot-scope="scope">
                      <div v-if="scope.row.user_info.length == '0' || !scope.row.user_info.length">
                        {{ "0.0" }}
                      </div>
                      <div v-if="scope.row.user_info.length == '1'">
                        <div v-for="(val,i) in scope.row.user_info" :key="i"> 
                          {{ val.spend_week[v]}}
                        </div>
                      </div>
                      <div v-if="scope.row.user_info.length > '1'">
                        <div v-for="(val,i) in scope.row.user_info" :key="i" class="borders">
                          <span v-if="val.spend_week[v]">
                            {{ val.spend_week[v].toFixed(1) }}
                          </span>
                          <span v-else>
                            {{ '0.0' }}
                          </span>
                        </div>
                      </div>
                  </template>
              </el-table-column>
            </el-table>
            <el-pagination 
              v-show="tableTotal > 12" 
              background 
              layout="prev, pager, next" 
              :page-size="params.pageSize" 
              @size-change="pageSizeChange1" 
              @current-change="pageNoChange1" 
              :current-page="params.pageNo" 
              style="text-align: center" 
              :total="tableTotal">
            </el-pagination>
          </el-tab-pane>
          <el-tab-pane label="部门列表" name="second">
            <el-row style="margin: 25px 0 25px 0px">
              <el-col :xs="24" :sm="12" :lg="6">
              <!-- <el-radio v-model="radio" :label="1" style="width: 100%"> -->
                  部门：
                  <el-select style="width:65%" v-model="selectedDep" placeholder="请选择" @change="changeSelect" filterable multiple collapse-tags>
                    <el-option
                      v-for="(v,i) in departmentFilterData"
                      :key="i"
                      :label="v.name"
                      :value="v.id">
                    </el-option>
                  </el-select>
              <!-- </el-radio> -->
            </el-col>
            <el-col :xs="24" :sm="8" :lg="8" class="col-box">
                  <span class="col-span">时间段：</span>
                  <el-date-picker
                      v-model="dateRange1"
                      @change="changeDateRange1"
                      type="daterange"
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期">
                  </el-date-picker>
                </el-col>
                <el-button type="warning" round style="margin-left:30%" @click="down1">导出</el-button>
            </el-row>
            <el-table
              :key="Math.random()"
              ref="table"
              :data="tableData1"
              border
              style="width: 100%;margin:10px 0px 10px 0px"
              :header-cell-style="{ background: '#eef1f6',height:'80px' }"
              :row-class-name="tableRowClassName"
              min-height='300'
            >
              <el-table-column label="一级部门" width="180" align="center" fixed="left">
                  <template slot-scope="scope">
                      {{ scope.row.dept_name}}
                  </template>
              </el-table-column>

              <el-table-column label="需求 / 实际" width="180" align="center" fixed="left">
                  <div class="borders">需求</div>
                  <div class="borders">实际</div>
                  <div style="width: 187px;margin:10px 0px 5px -14px;">GAP</div>
              </el-table-column>

              <el-table-column align="center" v-for="(val,i) in weekList1" :key="i" :prop="val" :label="week2date(val)" width="180">
                  <template slot-scope="scope">
                    <div v-if="!scope.row.GAP[val]">{{"-"}}</div>
                    <div v-else>
                      <div class="borders">{{ scope.row.GAP[val].need.toFixed(1) }}</div>
                      <div class="borders">{{ scope.row.GAP[val].get.toFixed(1) }}</div>
                      <div style="width: 182px;margin:10px 0px 5px -14px;">{{ (scope.row.GAP[val].need - scope.row.GAP[val].get).toFixed(1)}}</div>
                    </div>
                  </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getHeaderName } from '@/app.config'
import Cookies from 'js-cookie';
import VTitle from '@/views/sys/internetThings/title';
import { mapState, mapMutations } from 'vuex';
import http from '@/views/sys/axios';
import { Loading } from 'element-ui';
import { DateUtil } from './utils.js'

export default {
  name: 'gapSum',
  components: {
    VTitle,
  },
  data() {
    return {
      statusOptions:[
        {'label':'变更','value':0},
        // {'label':'封存','value':1},
        {'label':'结项','value':2},
        {'label':'立项','value':3},
        // {'label':'终止','value':4},
        {'label':'研发结项','value':5},
        {'label':'预立项','value':6},
        // {'label':'潜在项目','value':7},
      ],
      value2:'',
      props: { multiple: true },
      singleSelector:[],
      departmentFilterData:[],
      radio: 1,
      selectedDep: '',
      tableData1:[],
      activeName: 'first',
      tableTotal:0,
      params: {
        pageNo: 1,
        pageSize: 12,
        dept_ids:[]
      },
      temp:[],
      projectList:[],
      start_date: '',
      end_date: '' ,
      start_date1: '',
      end_date1: '' ,
      dateRange: [],
      dateRange1: [],
      pramData:{},
      pramData1:{},
      loading: false,
      tableData: [],
      weekList:[],
      weekList1:[],
    };
  },
  created(){
    this.getOptions()
    this.defaultWeekTime()
    this.getTableData()
    this.getTableData1()
  },
  mounted(){
    this.getDepartmentFilter()
  },
  watch:{
  },
  methods: {
    filterStatus(e){
      console.log(e)
      this.pramData['status'] = e
      this.params.pageNo = 1
      this.getTableData()
    },
    down1(res, name) {
        this.loading = true
        this.$axios({
          url: process.env.VUE_APP_SOURSE_MANAGE_HOST + '/api/v1/business_project_requirements_to_excel',
          method: "get",
          headers: getHeaderName(),
          responseType: 'blob',
        }).then(res => {
          if(res.status === 200) {
            const blob = new Blob([res.data]);
            const fileName = '资源看板-业务维度(部门列表).xls';
            // for IE
          if (window.navigator && window.navigator.msSaveOrOpenBlob) {
              window.navigator.msSaveOrOpenBlob(blob, fileName)
          } else {
              // for Non-IE (chrome, firefox etc.)
              const elink = document.createElement('a');
              elink.download = fileName;
              elink.style.display = 'none';
              elink.href = URL.createObjectURL(blob);
              document.body.appendChild(elink);
              elink.click();
              URL.revokeObjectURL(elink.href);
              document.body.removeChild(elink);
              this.loading = false
              this.$message({
              type:"success",
              message:"导出成功!"
            })
          } 
          } else {
            this.loading = false
            this.$message.error('下载出错了!'); 
          }
        }).catch(err => {
            this.$message.error('下载出错了!'); 
            this.loading = false
        })
      },
    down(res, name) {
        this.loading = true
        this.$axios({
          url: process.env.VUE_APP_SOURSE_MANAGE_HOST + '/api/v1/project_info_to_excel',
          method: "get",
          headers: getHeaderName(),
          responseType: 'blob',
        }).then(res => {
          if(res.status === 200) {
            const blob = new Blob([res.data]);
            const fileName = '资源看板-业务维度(项目列表).xls';
            // for IE
          if (window.navigator && window.navigator.msSaveOrOpenBlob) {
              window.navigator.msSaveOrOpenBlob(blob, fileName)
          } else {
              // for Non-IE (chrome, firefox etc.)
              const elink = document.createElement('a');
              elink.download = fileName;
              elink.style.display = 'none';
              elink.href = URL.createObjectURL(blob);
              document.body.appendChild(elink);
              elink.click();
              URL.revokeObjectURL(elink.href);
              document.body.removeChild(elink);
              this.loading = false
              this.$message({
              type:"success",
              message:"导出成功!"
            })
          }
          } else {
            this.loading = false
            this.$message.error('下载出错了!'); 
          }
        }).catch(err => {
            this.$message.error('下载出错了!'); 
            this.loading = false
        })
      },
    changeSelect(val){
      this.pramData1['dept_ids'] = val
      this.getTableData1()
    },
    getDepartmentFilter() {
        this.$axios({
          url: process.env.VUE_APP_SOURSE_MANAGE_HOST + '/api/v1/department/list',
          method: "get",
          headers: getHeaderName(),
          params: {
            type: 'own'
          }
        }).then(res => {
          if(res.data.code === 200) {
            this.departmentFilterData = res.data.data
          }
        }).catch(error => {
          console.log(error)
        })
    },
    getTableData1(){
      this.loading = true
      this.pramData1['week_range'] = this.weekList1.join()
      this.$axios({
          url: process.env.VUE_APP_SOURSE_MANAGE_HOST + '/api/v1/business_project_requirements',
          method: "post",
          headers: getHeaderName(),
          data:this.pramData1
      }).then(res => {
        if(res.data.code === 200){
          this.loading = false
          this.tableData1 = res.data.data.data 
        }else{
          this.loading = false
          this.$message.error.msg
        }
      })
    },
    addClass({row, column, rowIndex, columnIndex}){
      // console.log("row",row.user_info)
      // if(columnIndex > 4) {
      //   let spendTime = 0
          // if(row.week_spend[column.property]){
          //       spendTime = Number(row.week_spend[column.property])
          //     if(spendTime < 1 && spendTime > 0){
          //       return 'cell-one'
          //     }
          //     if(spendTime == 1){
          //       return ''
          //     }
          // }else{
          //   return 'cell-zore'
          // }
      // }
    },
    handleClick(tab, event) {
      // console.log(tab, event);
    },
    pageSizeChange1(val) {
      this.params.pageSize = val
      this.getTableData()
    },
    pageNoChange1(val) {
      this.params.pageNo = val
      this.getTableData()
    },
    tableRowClassName({row, rowIndex}) {
      if (rowIndex%2 === 0) {
        return 'warning-row';
      } 
      return '';
    },
    searchPro(e){
      this.projectList = [] // 清空参数
      e.map((v,i) => {
        this.projectList.push(v[1])
      })
      this.params.pageNo = 1
      this.getTableData()
    },
    week2date(val) {
        let arr = val.split("-")
        let year = arr[0]
        let week = arr[1]
        let betDay = new Date(year+1+'-01-01 00:00:00').getTime() - new Date(year+'-01-01 00:00:00').getTime()
        let newD1 = new Date(year,0,1)
        let newD2 = new Date(year,11,31)
        let dayMS=24*60*60*1000
        let firstDay=firstDay=(7-newD1.getDay())*dayMS
        let weekMS=0
        if(newD1.getDay() < 4) {
            weekMS=(week-2)*7*dayMS
        } else {
            weekMS=(week-1)*7*dayMS
        }
        let result=newD1.getTime()+firstDay+weekMS+5*dayMS
        newD1.setTime(result)
         return val + '周\n(' + newD1.getFullYear() + "/" + (newD1.getMonth()+1) + "/" +newD1.getDate() + ')'
    },
    defaultWeekTime() {
        let startD = new Date()
        let endD = new Date()
        endD.setMonth(endD.getMonth() + 1)
        let beginDate = startD.getFullYear()+'-'+(startD.getMonth()+1)+'-'+startD.getDate()
        let endDate = endD.getFullYear()+'-'+(endD.getMonth()+1)+'-'+endD.getDate()
        this.dateRange = [beginDate,endDate]
        this.dateRange1 = [beginDate,endDate]
        this.weekList = DateUtil.estLabourWeek(beginDate,endDate)
        this.weekList1 = DateUtil.estLabourWeek(beginDate,endDate)
    },
    changeDateRange(e) {
      let list = []
      if(e) {
        list = DateUtil.estLabourWeek(e[0],e[1])
      }
      this.pramData.pageNo = 1
      this.weekList = list
      this.getTableData()
    },
    changeDateRange1(e) {
      let list = []
      if(e) {
        list = DateUtil.estLabourWeek(e[0],e[1])
      }
      this.weekList1 = list
      this.getTableData1()
    },
    getOptions(){
      this.$axios({
          url: process.env.VUE_APP_SOURSE_MANAGE_HOST + '/api/v1/project_list',
          method: "get",
          headers: getHeaderName(),
      }).then((res => {
          this.singleSelector = res.data.message
      }))
    },
    getTableData(){ 
      this.loading = true
      this.pramData['week_range'] = this.weekList.join()
      this.pramData['project_ids'] = this.projectList
      this.pramData['pageNo'] = this.params.pageNo
      this.$axios({
          url: process.env.VUE_APP_SOURSE_MANAGE_HOST + '/api/v1/project_info',
          method: "post",
          headers: getHeaderName(),
          data:this.pramData
      }).then((res => {
        if(res.data.code === 200){
          this.loading = false
          this.tableData = res.data.data.form_data
          this.tableTotal = res.data.data.totalCount
        }else{
          this.loading = false
          this.$message.error(res.data.message)
        } 
      }))
  }
  },
};
</script>

<style lang="scss" scoped>
/deep/ .el-table td.cell-one { 
  background-color:#feecbade  !important;
  color: #82848a;
}
/deep/ .el-table td.cell-zore { 
  background-color:#eb070763 !important;
  color: #82848a;
}
/deep/.el-table .warning-row {
    background: oldlace;
  }
/deep/.el-table--enable-row-transition .el-table__body td {
  padding: 0px;
  height: 43px
}
/deep/th.gutter{
  width:  23px !important;
  display: block !important;
}
/deep/td:first-child .cell {
    // padding-left: 10px;
    padding: 15px 0 15px 10px;
}

.col-box {
  display: flex;
  margin-bottom: 10px;
  .col-span {
    // margin-right: 10px;
    line-height: 36px;
  }
}
.borders{
  border-bottom: 1px solid #c5c4c1;
  height: 40px;
  width: 183px;
  margin-left: -14px;
  margin-top:10px;
  // margin-bottom:10px;
}
#gapsum {
  padding: 32px;
  background-color: rgb(240, 242, 245);
  position: relative;
  //   .btn-group {
  //     position: relative;
  //     .edit {
  //       position: absolute;
  //       top: 50%;
  //       right: -2%;
  //       transform: translate(-50%, -50%);
  //     }
  //   }
}
</style>